<template>
    <div class="flex items-center">
        <div class="w-194px">
            <el-select v-model="selectedProvince.name" placeholder="请选择省份" @change="handleProvinceChange">
                <el-option v-for="province in provinces" :key="province.id" :label="province.name" :value="province.id">
                </el-option>
            </el-select>
        </div>
        <div class="w-194px ml-12px">
            <el-select v-model="selectedCity" placeholder="请选择城市" clearable>
                <el-option v-for="city in filteredCities" :key="city.id" :label="city.name" :value="city.name">
                </el-option>
            </el-select>
        </div>
    </div>
</template>

<script setup lang="ts">
import { provinces, cities } from '@/utils/provinces'

const selectedProvince = reactive({
    id: '',
    name: ''
}); // 修改初始值为空字符串

const selectedCity = ref<string>(''); // 修改为 string 类型，初始为空字符串

// 根据所选省份动态获取城市列表
const filteredCities = computed((): City[] => {
    const provinceId = Number(selectedProvince.id) // 转换为 number 类型
    if (!provinceId) return []
    return cities[provinceId] || []
});

// 省份变化时重置城市选择
const handleProvinceChange = (value: any) => {
    const provinceId = value

    // 从 provinces 中查找对应的省份对象
    const provinceObj = provinces.find(p => p.id === provinceId)

    if (provinceObj) {
        selectedProvince.id = String(provinceObj.id) // 转换为字符串
        selectedProvince.name = provinceObj.name
    } else {
        selectedProvince.id = ''
        selectedProvince.name = ''
    }

    selectedCity.value = ''
};

watch(() => selectedProvince.name,(newVal) => {
    const p = provinces.find(p => p.name === newVal)
    if (p) {
        selectedProvince.id = String(p.id)
    } else {
        selectedProvince.id = ''
    }
})

defineExpose({
    selectedProvince,
    selectedCity
})
</script>

<style scoped></style>